package com.wushi.lenovo.asia5b.app_ui.inbox.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mvp.base.BaseMvpFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.refresh.AutoRefreshLayout;
import com.mvp.refresh.RefreshViewManager;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.inbox.mvpview.InboxMsgFragmentView;
import com.wushi.lenovo.asia5b.app_di.inbox.presenter.InboxMsgFragmentPresenter;
import com.wushi.lenovo.asia5b.app_event.ChangeInboxEvent;
import com.wushi.lenovo.asia5b.app_event.ReadNotificationEvent;
import com.wushi.lenovo.asia5b.app_model.inbox.InboxMsgModel;
import com.wushi.lenovo.asia5b.app_model.inbox.InboxMsgType;
import com.wushi.lenovo.asia5b.app_model.inbox.SInboxMsgModel;
import com.wushi.lenovo.asia5b.app_ui.h5.CategoryActivity;
import com.wushi.lenovo.asia5b.app_ui.inbox.activity.InboxActivity;
import com.wushi.lenovo.asia5b.app_ui.inbox.adapter.InboxMsgAdapter;
import com.wushi.lenovo.asia5b.app_utils.helper.UriHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import timber.log.Timber;

/**
 * Created by zhangyuncai on 2019/1/8.
 */
public class InboxMsgFragment extends BaseMvpFragment<InboxMsgFragmentView, InboxMsgFragmentPresenter>
        implements InboxMsgFragmentView {
    @BindView(R.id.recyclerview_inbox)
    RecyclerView mRecyclerView;
    @BindView(R.id.auto_inbox)
    AutoRefreshLayout auto;
    private InboxMsgAdapter mAdapter;
    private final List<InboxMsgModel> mDatas = new ArrayList<>();
    private View emptyView;
    private InboxMsgType inboxMsgType;

    public static InboxMsgFragment newInstance(Context context, InboxMsgType inboxMsgType) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(CommonConstant.InboxMsgType, inboxMsgType);
        return (InboxMsgFragment) Fragment.instantiate(context, InboxMsgFragment.class.getName(), bundle);
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_inbox;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        inboxMsgType = (InboxMsgType) getArguments().getSerializable(CommonConstant.InboxMsgType);
        initView();
        initEvent();
    }

    @Override
    protected void lazyFetchData() {
        initData();
    }

    @Override
    protected void initView() {
        if (auto != null)
            ((RefreshViewManager) mActivity).addView(auto);
        emptyView = View.inflate(getContext(), R.layout.empty_voucher, null);
        TextView tv_empty_start = emptyView.findViewById(R.id.tv_empty_start);
        if (inboxMsgType == InboxMsgType.inbox) {
            tv_empty_start.setText(R.string.inbox_empty);
            if (auto != null) {
                auto.setEnableLoadMore(false);
                auto.setEnableRefresh(false);
            }
        } else {
            tv_empty_start.setText(R.string.inbox_order_empty);
        }
        mAdapter = new InboxMsgAdapter(mDatas, inboxMsgType);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        if (UserRepository.isLogin()) {
            if (inboxMsgType == InboxMsgType.inbox) {
                getPresenter().getMsgInbox();
            } else {
                getMsgOrders(0);
            }
        }
    }

    private void getMsgOrders(int refresh) {
        getPresenter().getMsgOrders(refresh);
    }

    @Override
    protected void initEvent() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                InboxMsgModel item = mAdapter.getItem(position);
                if (!item.getCheck_read()) {
                    Timber.d("--->>>>>>>>---2/id:" + item.getId());
                    getPresenter().readNotifacation(item.getId(), inboxMsgType == InboxMsgType.inbox ? "promo_notification" : "order_notification");
                    EventBus.getDefault().post(new ReadNotificationEvent(item.getId(), inboxMsgType == InboxMsgType.inbox ? "promo_notification" : "order_notification"));
                }
                String detail_page_source_url = item.getDetail_page_source_url();
                Timber.d("--->>>>>>>>---detail_page_source_url:" + detail_page_source_url);
                if (inboxMsgType == InboxMsgType.order) {
//                    OrderDetailActivity.startOrderDetailActivity(getContext(), item.getOrder_id());
                    //默认跳转
                    String skipUrl = "asia5b://www.asia5b.com/orderList?id=0";
                    List<InboxMsgModel.Action> actionList = item.getAction();
                    if (actionList != null && actionList.size() > 0) {
                        for (InboxMsgModel.Action actionBean : actionList) {
                            if (TextUtils.equals(actionBean.getRedirect(), "my order")) {
                                //成功匹配关键词
                                skipUrl = actionBean.getUrl();
                                break;
                            }
                        }
                    }
                    UriHelper.parseUri(skipUrl, getContext());
                } else {
                    if (!TextUtils.isEmpty(detail_page_source_url)) {
                        CategoryActivity.startCategoryActivity(getContext(), detail_page_source_url, getString(R.string.inbox_inbox));
                    }
                }
            }
        });
        if (auto != null)
            auto.setOnRefreshListener(refreshLayout -> {
                getMsgOrders(1);
            });
        if (auto != null)
            auto.setOnLoadMoreListener(refreshLayout -> {
                getMsgOrders(2);
            });
    }

    @Override
    public void getMsgInboxResult(ResultModel<List<InboxMsgModel>> resultModel) {
        if (resultModel.isSuccess() && resultModel.getData() != null) {
            mDatas.addAll(resultModel.getData());
            int count_unread = resultModel.getCount_unread();
            ((InboxActivity) getActivity()).setTabCount(1, count_unread);
        }
        mAdapter.setEmptyView(emptyView);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void getMsgOrdersResult(ResultModel<SInboxMsgModel> resultModel, int currentPage) {
        if (resultModel.isSuccess() && resultModel.getData() != null && resultModel.getData().getData() != null) {
            if (currentPage <= 1) {
                mDatas.clear();
            }
            mDatas.addAll(resultModel.getData().getData());
            int total = resultModel.getData().getTotal();
            if (auto != null)
                auto.setEnableLoadMore(mDatas.size() < total);
        }
        mAdapter.setEmptyView(emptyView);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void readNotifacationResult(ResultModel resultModel, int notification_id) {
        if (resultModel.isSuccess()) {
            for (int i = 0; i < mDatas.size(); i++) {
                InboxMsgModel inboxMsgModel = mDatas.get(i);
                if (inboxMsgModel.getId() == notification_id) {
                    inboxMsgModel.setCheck_read("TRUE");
                    mAdapter.notifyItemChanged(i);
                    break;
                }
            }
            EventBus.getDefault().post(new ChangeInboxEvent(inboxMsgType));
        }
    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        super.dismissLoadingBar(dississTag);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }

    @Override
    public void showLoadingFailureError(Throwable throwable) {
        super.showLoadingFailureError(throwable);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }
}